package com.movies.service.controller.user;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.movies.service.common.Constants;
import com.movies.service.common.Result;
import com.movies.service.entity.Movies;
import com.movies.service.entity.Save;
import com.movies.service.entity.User;
import com.movies.service.service.MoviesService;
import com.movies.service.service.SaveService;
import com.movies.service.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/user/save")
@SaCheckLogin
public class UserSaveController {

    @Autowired
    private SaveService saveService;
    @Autowired
    private UserService userService;
    @Autowired
    private MoviesService moviesService;

//    分页查询当前用户的收藏列表（可按电影ID筛选）
    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer pageNo,
                       @RequestParam(defaultValue = "10") Integer pageSize,
                       @RequestParam(required = false) Long mid) {
        Long uid = StpUtil.getLoginIdAsLong();
        LambdaQueryWrapper<Save> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Save::getUid, uid).eq(mid != null, Save::getMid, mid);
        Page<Save> page = saveService.page(new Page<>(pageNo, pageSize), wrapper);
        return Result.success(page);
    }

//    检查是否已收藏某电影
    @GetMapping("/check")
    public Result check(@RequestParam Long mid) {
        Long uid = StpUtil.getLoginIdAsLong();
        long count = saveService.count(new LambdaQueryWrapper<Save>().eq(Save::getUid, uid).eq(Save::getMid, mid));
        return Result.success(count > 0);
    }

//    添加收藏
    @PostMapping
    public Result add(@RequestBody AddReq req) {
        if (req.getMid() == null) {
            return Result.error(Constants.CODE_600, "缺少电影ID");
        }
        Long uid = StpUtil.getLoginIdAsLong();
        long count = saveService.count(new LambdaQueryWrapper<Save>().eq(Save::getUid, uid).eq(Save::getMid, req.getMid()));
        if (count > 0) {
            return Result.error(Constants.CODE_300, "已收藏");
        }
        User user = (User) StpUtil.getSession().get("user");
        if (user == null) { user = userService.getById(uid); }
        Movies m = moviesService.getById(req.getMid());
        Save s = new Save();
        s.setUid(uid);
        s.setMid(req.getMid());
        s.setMname(req.getMname() != null ? req.getMname() : (m != null ? m.getMname() : null));
        boolean ok = saveService.save(s);
        return ok ? Result.success("收藏成功", s) : Result.error(Constants.CODE_600, "收藏失败");
    }

//    删除收藏（按收藏ID）
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        Long uid = StpUtil.getLoginIdAsLong();
        Save s = saveService.getById(id);
        if (s == null || !uid.equals(s.getUid())) {
            return Result.error(Constants.CODE_401, "无权操作该收藏");
        }
        boolean ok = saveService.removeById(id);
        return ok ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

//    删除收藏（按电影ID）
    @DeleteMapping("/movie/{mid}")
    public Result deleteByMovie(@PathVariable Long mid) {
        Long uid = StpUtil.getLoginIdAsLong();
        boolean ok = saveService.remove(new LambdaQueryWrapper<Save>().eq(Save::getUid, uid).eq(Save::getMid, mid));
        return ok ? Result.success("删除成功") : Result.error(Constants.CODE_600, "删除失败");
    }

    /** 添加收藏请求体 */
    public static class AddReq {
        private Long mid;
        private String mname;
        public Long getMid() { return mid; }
        public void setMid(Long mid) { this.mid = mid; }
        public String getMname() { return mname; }
        public void setMname(String mname) { this.mname = mname; }
    }
}